<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2022/5/4} {9:12} 
 */

namespace app\index\controller;



use app\index\model\WechatUserModel;
use think\Db;
use think\Request;
use wanghua\general_utility_tools_php\tool\Tools;

class BaseAuthController extends BaseCommonController
{

    public function __construct()
    {
        parent::__construct();


        //首页提示语
        $this->assign('index_msg',cache('index_msg_alert_cache_time'));

        //线上环境加载微信授权
        if(config('sys_env') == 'PROD'){
            $wx_user_info = session('wx_user_info');
            if(empty($wx_user_info['openid'])) {
                //重定向之前，保存当前url, 在获取授权信息之后，回跳到授权之前的网页地址
                session('redirect_before_url_session',request()->url(true));
                $ver = Tools::get_thinkphp_version();
                if($ver == '5.0'){
                    $url = url('Wexinauth/usrAuth','',false,true);
                }else{
                    $url = request()->domain().url('Wexinauth/usrAuth');
                }
                //没有则重定向去授权
                return $this->redirect($url);
            }
            $this->saveWechatUser($wx_user_info);
        }


        //校验系统维护状态 start
        $chm = $this->checkMaintain();
        if($chm['is_maintain']){
            if($chm['openid']){
                //解析openid
                if(!in_array(index_user_openid(), explode(',',$chm['openid']))){
                    //白名单之外维护中
                    //Tools::log_to_write_txt([
                    //    '维护测试'=>$chm['openid'],
                    //    'my'=>index_user_openid()
                    //]);
                    return $this->error($chm['msg']);
                }
            }else{
                //不存在，直接维护中
                return $this->error($chm['msg'].'！');
            }
        }
        //校验系统维护状态 end


    }




    /**
     * desc：
     * author：wh
     * @param $wx_user_info
     */
    private function saveWechatUser($wx_user_info){
        try {
            $wechat_user = WechatUserModel::getWxUserByOpenid($wx_user_info['openid']);
            if(empty($wechat_user)){
                WechatUserModel::insertInfoToSaveSession($wx_user_info);
                return null;
            }
            //扩展，按周期更新,而不是不更新
            if(empty($wechat_user['update_time']) || time()-strtotime($wechat_user['update_time'])>5*3600){

                WechatUserModel::updateUserToSaveSession($wx_user_info);
                return null;
            }


        }catch (\Exception $e){
            Tools::log_to_write_txt([
                'error'=>'存储异常.'.$e->getMessage(),
                'wx_user_info'=>$wx_user_info,
                'error_info'=>$e->getTraceAsString()
            ]);
        }
    }
}